package com.qikecn.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.encrypt.AesException;

import cn.geekapp.utils.RandomUtils;
import cn.geekapp.utils.StringUtils;

public class WeixinJSSDKUtil {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//System.out.println("getJsapi_ticket"+getJsapi_ticket());
		String string1 = "jsapi_ticket=HoagFKDcsGMVCIY2vOjf9uFufEZ4N50O7l5mfGW5tV2TnhtDAScmuLwztQUlU1De9uJt4yEArLYyXb0iEksiGw&noncestr=95fd0e3e-21fe-4511-8a2d-ce3465f52fab&timestamp=1497018581&url=http://vipcard.aituring.com/wxcard/download/index.html?from=groupmessage&isappinstalled=0";
		try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            String signature = byteToHex(crypt.digest());
            System.out.println("signature:"+signature);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
		
	}
	
	//static final String appId = "wx32b0e54aa3f5669a";
	//static final String appSecret = "8d9c261d3e7c36b1a8ed2be8a8555a9f";
	
	static String access_token = "";
	//static long access_token_lasttime = 0L;
	public static String getAccess_token(){
		/*if(!StringUtils.isEmpty(access_token) && System.currentTimeMillis() - access_token_lasttime < 7200 * 1000L){
			return access_token;
		}
		String url = "https://api.weixin.qq.com/cgi-bin/token";
		String result = HttpClientUtil.sendGet(url, "grant_type=client_credential&appid="+ appId + "&secret=" + appSecret);
		System.out.println("getAccess_token result="+result);
		
		try {
			JSONObject jsonObject = new JSONObject(result);
			if(jsonObject.has("access_token")){
				access_token = jsonObject.getString("access_token");
				access_token_lasttime = System.currentTimeMillis();
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}*/
		
		access_token = AccessTokenApi.getAccessTokenStr();
		return access_token;
	}
	
	static String apiticket = "";
	static long apiticket_lasttime = 0L;
	public static String getJsapi_ticket(){
		if(!StringUtils.isEmpty(apiticket) && System.currentTimeMillis() - apiticket_lasttime < 7200 * 1000L){
			return apiticket;
		}
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
		String result = HttpClientUtil.sendGet(url, "access_token=" + getAccess_token() + "&type=jsapi");
		System.out.println("getJsapi_ticket result="+result);
		try {
			JSONObject jsonObject = new JSONObject(result);
			if(jsonObject.has("ticket")){
				apiticket = jsonObject.getString("ticket");
				apiticket_lasttime = System.currentTimeMillis();
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return apiticket;
	}
	
	//获取时间戳
	private static String create_timestamp() {
	    return Long.toString(System.currentTimeMillis() / 1000);
	}
	//获取随机字符串
	private static String create_nonce_str() {
	    //return UUID.randomUUID().toString();
		return RandomUtils.getRandomNumbersAndLetters(16);
	}
	
    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        // 注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str
                + "&timestamp=" + timestamp + "&url=" + url;
        
        System.out.println("string1:"+string1);

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
            System.out.println("signature:"+signature);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
    
    /**
     * 用SHA1算法生成安全签名
     * 
     * @param token
     *            票据
     * @param timestamp
     *            时间戳
     * @param nonce
     *            随机字符串
     * @param encrypt
     *            密文
     * @return 安全签名
     * @throws NoSuchAlgorithmException
     * @throws AesException
     */
    public static String getSHA1(String token, String timestamp, String nonce)
            throws NoSuchAlgorithmException {
        String[] array = new String[] { token, timestamp, nonce };
        StringBuffer sb = new StringBuffer();
        // 字符串排序
        Arrays.sort(array);
        for (int i = 0; i < 3; i++) {
            sb.append(array[i]);
        }
        String str = sb.toString();
        // SHA1签名生成
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(str.getBytes());
        byte[] digest = md.digest();

        StringBuffer hexstr = new StringBuffer();
        String shaHex = "";
        for (int i = 0; i < digest.length; i++) {
            shaHex = Integer.toHexString(digest[i] & 0xFF);
            if (shaHex.length() < 2) {
                hexstr.append(0);
            }
            hexstr.append(shaHex);
        }
        return hexstr.toString();
    }
	

}
